---
--- @File     : img_zoom
--- @Time     : 2023-09-11 22:04:45
--- @Docs     : 拓展 -> 图片缩放
require "import"
import "android.graphics.Matrix"
import "android.graphics.PointF"
import "android.util.FloatMath"

ZoomPage = {
    LinearLayout,
    gravity = "center",
    layout_width = "fill",
    layout_height = "fill",
    {
        ImageView,
        layout_width = "100%w",
        id = "iv",
        src = "https://s1.ax1x.com/2023/01/27/pSUV6RH.jpg",
        scaleType = "matrix",
        layout_height = "100%w",
    },
};

--activity.setContentView(布局)

local matrix = Matrix()
local savedMatrix = Matrix()
local mode = 0
local startPoint = PointF()
local midPoint = PointF();
local oriDis = 1

local distance = function(e)
    local x = e.getX(0) - e.getX(1)
    local y = e.getY(0) - e.getY(1)
    return FloatMath.sqrt(x * x + y * y)
end

local middle = function(e)
    local x = e.getX(0) + e.getX(1)
    local y = e.getY(0) + e.getY(1)
    return PointF(x / 2, y / 2)
end

iv.onTouch = function(v, e)
    local a = e.getAction() & 255
    if a == MotionEvent.ACTION_DOWN then
        matrix.set(v.getImageMatrix())
        savedMatrix.set(matrix)
        startPoint.set(e.getX(), e.getY())
        mode = 1
    end
    if a == MotionEvent.ACTION_POINTER_DOWN then
        oriDis = distance(e);
        if oriDis > 10 then
            savedMatrix.set(matrix);
            midPoint = middle(e)
            mode = 2
        end
    end
    if a == MotionEvent.ACTION_POINTER_UP then
        mode = 0
    end
    if a == MotionEvent.ACTION_MOVE then
        if (mode == 1) then
            matrix.set(savedMatrix);
            matrix.postTranslate(e.getX() - startPoint.x, e.getY() - startPoint.y);
        elseif (mode == 2) then
            local newDist = distance(e);
            if (newDist > 10) then
                matrix.set(savedMatrix);
                local scale = newDist / oriDis
                matrix.postScale(scale, scale, midPoint.x, midPoint.y);
            end
        end
    end
    v.setImageMatrix(matrix)
    return true
end

return ZoomPage